package com.lyons.easyweb.modular.menu.service.impl;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.lyons.easyweb.core.util.RedisOperator;
import com.lyons.easyweb.modular.menu.dao.MenuMapper;
import com.lyons.easyweb.modular.menu.pojo.Menu;
import com.lyons.easyweb.modular.menu.pojo.MenuVo;
import com.lyons.easyweb.modular.menu.pojo.TreeModel;
import com.lyons.easyweb.modular.menu.pojo.TreeUtil;
import com.lyons.easyweb.modular.menu.service.MenuService;
import com.lyons.easyweb.modular.menu.vo.resp.MenuVoResp;
import com.lyons.easyweb.modular.role.pojo.RoleMenu;
import com.lyons.easyweb.modular.role.service.RoleMenuService;
import com.lyons.easyweb.modular.setting.pojo.Setting;
import com.lyons.easyweb.modular.setting.service.SettingService;
import com.lyons.easyweb.modular.user.pojo.SysUser;
import com.lyons.easyweb.modular.user.service.UserService;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author Lyons
 * @since 2021-07-01
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

	@Autowired
	private RoleMenuService roleMenuService;

	@Autowired
	private SettingService settingService;

	@Autowired
	private UserService userService;

	@Autowired
	private RedisOperator redis;

	/**
	 * 查询所有菜单数据（layui mini 菜单显示使用）[更具用户授予的角色查询菜单数]
	 */
	@Override
	public Map<String, Object> listMenu(String userId) {

		String key = "system:menu:" + userId;

		if (redis.exists(key)) {

			String json = redis.get(key);
			return JSON.parseObject(json, new TypeReference<LinkedHashMap<String, Object>>() {
			});
		}

		// 存储树形菜单结婚
		Map<String, Object> treeDataMap = new LinkedHashMap<>(16);
		Map<String, Object> homeInfo = new LinkedHashMap<>(16);
		Map<String, Object> logoInfo = new LinkedHashMap<>(16);

		List<Menu> menuList;

		// 判断用户是否是超级管理员
		SysUser user = userService.getById(userId);
		if (user.getAccount().equals("superAdmin")) {

			// 查询所有的菜单
			menuList = baseMapper.selectList(new QueryWrapper<Menu>());
		} else {

			// 按照用户权限查询菜单信息
			menuList = baseMapper.queryRoleMenuByUserId(userId);
		}

		List<MenuVo> menuInfo = new ArrayList<>();
		for (Menu e : menuList) {
			MenuVo menuVO = new MenuVo();

			menuVO.setId(e.getId());
			menuVO.setPid(e.getPid());
			menuVO.setHref(e.getRouter());
			menuVO.setTitle(e.getName());
			menuVO.setIcon(e.getIcon());
			menuVO.setTarget("_self");

			menuInfo.add(menuVO);
		}

		treeDataMap.put("menuInfo", TreeUtil.toTree(menuInfo, "0"));

		Setting setting = settingService.querySettingInfo();

		homeInfo.put("title", "首页");
		homeInfo.put("href", "/page/welcome.html");// 控制器路由,自行定义

		logoInfo.put("title", setting.getSitename());
		if (ObjectUtils.isEmpty(setting.getLogo())) {
			logoInfo.put("image", "/images/logo.png");// 静态资源文件路径,可使用默认的logo.png
		} else {
			logoInfo.put("image", setting.getLogo());// 静态资源文件路径,可使用默认的logo.png
		}

		treeDataMap.put("homeInfo", homeInfo);
		treeDataMap.put("logoInfo", logoInfo);

		if (treeDataMap.size() > 0) {
			redis.set(key, JSON.toJSONString(treeDataMap), MenuService.class.getSimpleName());
		}

		return treeDataMap;
	}

	// ztree，角色授权使用
	@Override
	public List<TreeModel> queryAllModules(String roleId) {

		List<Menu> parentList = this.list(new QueryWrapper<Menu>().lambda().select(Menu::getId, Menu::getPid, Menu::getName));
		List<RoleMenu> roleMenuList = roleMenuService.list(new QueryWrapper<RoleMenu>().lambda().eq(RoleMenu::getRoleId, roleId));

		List<TreeModel> list = Lists.newArrayList();
		for (Menu menu : parentList) {

			TreeModel mode = new TreeModel(menu.getId(), menu.getPid(), menu.getName());

			if (roleMenuList.size() > 0) {
				for (RoleMenu rm : roleMenuList) {
					if (rm.getMenuId().equals(menu.getId())) {
						mode.setChecked(true);
					}
				}
			}
			list.add(mode);
		}
		return list;
	}

	// xm-select 查询菜单树 ------ 有bug
	public List<MenuVoResp> queryMenuList(String roleId, String mid) {

		// 排序，查询所有菜单
		List<Menu> list = list(new LambdaQueryWrapper<Menu>().select(Menu::getId, Menu::getName, Menu::getPid).orderByDesc(Menu::getSort));

		List<MenuVoResp> rootMenu = list.stream().map(e -> {
			MenuVoResp vo = new MenuVoResp();
			BeanUtils.copyProperties(e, vo);
			if (!ObjectUtils.isEmpty(mid) && mid.equals(vo.getId())) {
				vo.setSelected(true);
			} else {
				vo.setSelected(false);
			}
			return vo;
		}).collect(Collectors.toList());

		// 遍历获得 一级 菜单
		List<MenuVoResp> menuList = rootMenu.stream().filter(e -> e.getPid().equals("0")).collect(Collectors.toList());
		for (MenuVoResp menu : menuList) {

			menu.setChildren(getChild(menu.getId(), rootMenu));
		}

		return menuList;
	}

	public List<MenuVoResp> getChild(String id, List<MenuVoResp> rootMenu) {

		List<MenuVoResp> childList = Lists.newArrayList();

		rootMenu.forEach(menu -> {
			if (id.equals(menu.getPid())) {
				menu.setChildren(getChild(menu.getId(), rootMenu));
				childList.add(menu);
			}
		});
		return childList;
	}

}
